<?
class PostingController extends Controller_Action{
    
    public function preDispatch() 
    {
        $user = $this->getVkUser();
        if (!$user) {
            $this->_redirect('/auth');
        }

        parent::preDispatch();
    }
    
    /**
     * Добавить пост в очередь
     * @throws Zend_Controller_Action_Exception 
     */
    public function addTurnAction(){
        $this->_disableView();
        if (!$this->_getParam('pid') && !$this->_getParam('tid')) {
            throw new Zend_Controller_Action_Exception('Параметр post id или Turn id не указаны');
        }
        if (!$this->_getParam('img')) {
            throw new Zend_Controller_Action_Exception('Параметр image не указан');
        }        
        if (!PostPeer::getInstance()->findById($this->_getParam('pid'))->count()) {
            throw new Zend_Controller_Action_Exception('Пост не найден');
        }
        
        // получаем объект очереди
        $Turn = TurnPeer::getInstance()->findById($this->_getParam('tid'))->current();
        
        if (!$Turn) {
            throw new Zend_Controller_Action_Exception('Очередь ' . $this->_getParam('tid') . ' не найдена');
        }
        
        // получаем время очереди
        $times = $Turn->getTurnTimeRowsetByTurnId();
        
        if (!$times->count()) {
            throw new Zend_Controller_Action_Exception('Не задано время для очереди ' . $Turn->getName());
        }
        
        $turnPost = TurnPostPeer::getInstance()->createRow();
        
        $nextDay = date('Y-m-d', time());
        
        $r = TurnPostPeer::getInstance()->findEmptyPosition($nextDay, $times, $Turn);
        
        $turnPost->turn_id = $Turn->getId();
        $turnPost->post_id = $this->_getParam('pid');
        $turnPost->user_id = $this->getVkUser()->getRow()->getId();
        $turnPost->post_date = $r['post_date'];
        $turnPost->post_time = $r['post_time'];
        $turnPost->image = $this->_getParam('img');
        $turnPost->text = $this->_getParam('text');
        $turnPost->is_posted = 0;
		$turnPost->created_at = date('Y-m-d H:i:s');
        $turnPost->save();
        
        $this->_log->info('Add post in turn: post - ' . $this->_getParam('pid') .', turn - ' . $Turn->getName() . ', date - ' . $r['post_date'] . ', time - ' . $r['post_time']);
        
        PostPeer::getInstance()->update(array('is_reposted'=>1), 'id = ' . $this->_getParam('pid'));
        
        $source = Page::getInstance()->getCurrentSource();
        $_SESSION[$source->key]['post'] = null;
        $this->_redirect('/index/' . $source->key);
    }
    
    /**
     * обрезает картинку и добавляет ватермарк
     */
    public function cropImageAction()
    {
        $this->_ajaxOnly();
        
        // проверяем параметр post id (pid)
        if (!$this->_getParam('pid') && !$this->_getParam('gid')) {
            throw new Zend_Controller_Action_Exception('Параметр post id или group id не указаны');
        }
        
        // скачиваем картинку
        if (!$this->_getParam('img')) {
            throw new Zend_Controller_Action_Exception('Параметр img не указан');
        }
        $filePutResult = file_put_contents('tmp/_t'.$this->_getParam('pid').'.jpg', file_get_contents($this->_getParam('img')));
        if ($filePutResult == false) {
            throw new Zend_Controller_Action_Exception('Не удалось скачать картинку '.$this->_getParam('img'));
        }
        $this->_log->info('Crop image: upload image of ' . $this->_getParam('img') . ' in /tmp/_t' . $this->_getParam('pid') . '.jpg');
        $image = 'tmp/_t' . $this->_getParam('pid') . '.jpg';
        // обрезаем картинку если нужно
        if (($crop = $this->_getParam('crop')) != 0) {
            $w = $crop['w'];
            $h = $crop['h'];
            $x = $crop['x'];
            $y = $crop['y'];
            $cropCmd = $w . 'x' . $h . "+$x+$y";
            $newImage = 'tmp/_c' . $this->_getParam('pid') . '.jpg';
            $cmd = '"' . $this->_config->img->magickpath . '" ' . $image . " -crop $cropCmd +repage $newImage";
            // выполняем команду
            exec($cmd);
            // удаляем старую картинку
            unlink($image);
            $image = $newImage;
            $this->_log->info('Crop image: use cmd "'.$cmd.'"');
        }
        
        // добавляем ватермарк
        if ($this->_getParam('gravity') != 'none') {
            $watermarkPath = $_SERVER['DOCUMENT_ROOT'] . '/images/groups/' . $this->_getParam('gid') . '/watermark.png';
            $cmd = '"'.$this->_config->img->compositepath.'" -gravity '
                    . $this->_getParam('gravity') . ' ' . $watermarkPath . ' ' . $image . ' images/post/' . $this->_getParam('pid') . '.jpg';
            // выполняем команду
            exec($cmd);
            // удаляем старую картинку
            unlink($image);
            $this->_log->info('Crop image: add watermark use cmd "' . $cmd . '"');
        } else {
            // копируем картинку
            copy($image, 'images/post/' . $this->_getParam('pid') . '.jpg');
            // удаляем старую картинку
            unlink($image);
        }
        
        $image = '/images/post/' . $this->_getParam('pid') . '.jpg';	
        $this->_log->info('Crop image: create image "' . $image . '"');
        $this->_setAjaxResponse(array('img_src'=>$image));		
    }
    
    /**
     * быстрый постинг на стену группы в VK 
     */
    public function postAction()
    {
        $this->_disableView();
        if (!$this->_getParam('pid') && !$this->_getParam('gid')) {
            throw new Zend_Controller_Action_Exception('Параметр post id или group id не указаны');
        }
        if (!$this->_getParam('img')) {
            throw new Zend_Controller_Action_Exception('Параметр image не указан');
        }
        // получаем сервер для сохранения фотографии
        $data = array(
            'gid' => $this->_getParam('gid'),
            'access_token' => $this->getVkUser()->getAccessToken()
        );
        $serverPhoto = $this->_vk->api('photos.getWallUploadServer', $data);
        $this->_log->info('Posting post: vk api request (photos.getWallUploadServer) params (' . $this->_vk->getStrParams() . '); response=' . $this->_vk->getStrResponse());
                
        // сохранеяем фотку на сервере VK
        $uploadUrl = Zend_Uri::factory($serverPhoto['upload_url']);
        $client = new Zend_Http_Client($uploadUrl);
        $image = $this->_getParam('img');
        if(false === strpos($image, 'http://')){
            if ($qp = strpos($image, '?')) {
                $image = $_SERVER['DOCUMENT_ROOT'] . substr($image, 0, $qp);
            } else {
                $image = $_SERVER['DOCUMENT_ROOT'] . $image;
            }
        }
        $client->setFileUpload($image, 'photo');
        $result = $client->request('POST');
        $response = Zend_Json::decode($result->getBody());
        
        // формируем данные
        $data = array(
            'gid' => $this->_getParam('gid'),
            'server' => $response['server'],
            'photo' => $response['photo'],
            'hash' => $response['hash'],
            'access_token' => $this->getVkUser()->getAccessToken()
        );
        // сохраняем картинку
        $wallPhoto = $this->_vk->api('photos.saveWallPhoto', $data);
	$this->_log->info('Posting post: vk api request (photos.saveWallPhoto) params (' . $this->_vk->getStrParams() . '); response=' . $this->_vk->getStrResponse());
        
        // постим
        $data = array(
            'owner_id' => '-' . $this->_getParam('gid'),
            'attachments' => $wallPhoto[0]['id'],
            'message' => $this->_getParam('text'),
            'from_group' => 1,
            'signed' => 0,
            'access_token' => $this->getVkUser()->getAccessToken()
        );
        if ($this->_getParam('captcha_sid') && $this->_getParam('captcha_key')) {
            $data['captcha_sid'] = $this->_getParam('captcha_sid');
            $data['captcha_key'] = $this->_getParam('captcha_key');
        }
        
        $wall = $this->_vk->api('wall.post', $data);
        
        if (isset($wall['captcha_sid'])) {
            $data['captcha_sid'] = $wall['captcha_sid'];
            $data['post_id'] = $this->_getParam('pid');
            if (isset($wall['captcha_key'])) {
                $data['captcha_key'] = $wall['captcha_key'];
            } elseif (isset($wall['captcha_img'])) {
                $data['captcha_img'] = $wall['captcha_img'];
            }
            $this->_log->info('Posting post: vk api returned captcha, redirect to accept.captcha');
            $this->_redirect('/posting/accept.captcha?' . http_build_query($data));
        }

        $this->_log->info('Posting post: vk api request (wall.post) params (' . $this->_vk->getStrParams() . '); response=' . $this->_vk->getStrResponse());

        $this->_post(
            $this->_getParam('gid'), 
            $this->_getParam('pid'), 
            $this->_getParam('text'), 
            $wallPhoto[0]['id'], 
            'http://vk.com/wall-' . $this->_getParam('gid') . '_' . $wall['post_id']
        );
    }
	
	public function addTurnInParserAction()
	{
		$this->_ajaxOnly();
		if (!$this->_getParam('id') && !$this->_getParam('tid') && !$this->_getParam('text') && !$this->_getParam('tag') && !$this->_getParam('gid')) {
			throw new Zend_Controller_Action_Exception('Параметр text, img, tag или gid не указаны');
		}
		$lastInsertId = PostPeer::getInstance()->AddPost(array(
			'source_id' => '3',
			'type' => 'image',
			'external_id' => $this->_getParam('id'),
			'title' => $this->_getParam('text'), 
			'image_url' => $this->_getParam('img'),
			'tag' => $this->_getParam('tag'),
			'created_at' => date('Y-m-d H:i:s'),
			'external_created_at' => $this->_getParam('created')
			)
		);
		
		$this->_log->info('Posting add turn in parser: DB add post = ' . $this->_getParam('id'));
		
		// получаем объект очереди
        $turn = TurnPeer::getInstance()->findById($this->_getParam('tid'))->current();
        
        if (!$turn) {
            throw new Zend_Controller_Action_Exception('Очередь ' . $this->_getParam('tid') . ' не найдена');
        }
        
        // получаем время очереди
        $times = $turn->getTurnTimeRowsetByTurnId();
        
        if (!$times->count()) {
            throw new Zend_Controller_Action_Exception('Не задано время для очереди ' . $turn->getName());
        }
        
        $turnPost = TurnPostPeer::getInstance()->createRow();
        
        $nextDay = date('Y-m-d', time());
        
        $r = TurnPostPeer::getInstance()->findEmptyPosition($nextDay, $times, $turn);
		
		$image = null;
		if ($this->_getParam('img')) {
			$filePutResult = file_put_contents('images/post/'.$lastInsertId.'.jpg', file_get_contents($this->_getParam('img')));
		    if ($filePutResult == false) {
		        throw new Zend_Controller_Action_Exception('Не удалось скачать картинку '.$this->_getParam('img'));
		    }
		    $this->_log->info('Posting add turn in parser: upload image of ' . $this->_getParam('img') . ' in images/post' . $lastInsertId . '.jpg');
		
		    $image = '/images/post/' . $lastInsertId . '.jpg';
		}
		
        $turnPost->turn_id = $turn->getId();
        $turnPost->post_id = $lastInsertId;
        $turnPost->user_id = $this->getVkUser()->getRow()->getId();
        $turnPost->post_date = $r['post_date'];
        $turnPost->post_time = $r['post_time'];
        $turnPost->image = $image;
        $turnPost->text = $this->_getParam('text');
        $turnPost->is_posted = 0;
		$turnPost->created_at = date('Y-m-d H:i:s');
        $turnPost->save();
        
        $this->_log->info('Add post in turn: post - ' . $lastInsertId .', turn - ' . $turn->getName() . ', date - ' . $r['post_date'] . ', time - ' . $r['post_time']);
        
        PostPeer::getInstance()->update(array('is_reposted'=>1), 'id = ' . $lastInsertId);
        
        $this->_setAjaxResponse('ok');
	}
	
	public function postInParserAction()
	{
		$this->_ajaxOnly();
		if (!$this->_getParam('id') && !$this->_getParam('text') && !$this->_getParam('img') && !$this->_getParam('tag') && !$this->_getParam('gid')) {
			throw new Zend_Controller_Action_Exception('Параметр text, img, tag или gid не указаны');
		}
		$lastInsertId = PostPeer::getInstance()->AddPost(array(
			'source_id' => '3',
			'type' => 'image',
			'external_id' => $this->_getParam('id'),
			'title' => $this->_getParam('text'), 
			'image_url' => $this->_getParam('img'),
			'tag' => $this->_getParam('tag'),
			'created_at' => date('Y-m-d H:i:s'),
			'external_created_at' => $this->_getParam('created')
			)
		);
		
		$this->_log->info('Posting post in parser: DB add post = ' . $this->_getParam('id'));
		
		// получаем сервер для сохранения фотографии
        $data = array(
            'gid' => $this->_getParam('gid'),
            'access_token' => $this->getVkUser()->getAccessToken()
        );
		
        $serverPhoto = $this->_vk->api('photos.getWallUploadServer', $data);
        $this->_log->info('Posting post in parser: vk api request (photos.getWallUploadServer) params (' . $this->_vk->getStrParams() . '); response=' . $this->_vk->getStrResponse());
                
        // сохранеяем фотку на сервере VK
		$filePutResult = file_put_contents('images/post/'.$lastInsertId.'.jpg', file_get_contents($this->_getParam('img')));
        if ($filePutResult == false) {
            throw new Zend_Controller_Action_Exception('Не удалось скачать картинку '.$this->_getParam('img'));
        }
        $this->_log->info('Posting post in parser: upload image of ' . $this->_getParam('img') . ' in images/post' . $lastInsertId . '.jpg');
		
        $image = $_SERVER['DOCUMENT_ROOT'] . '/images/post/' . $lastInsertId . '.jpg';
        $uploadUrl = Zend_Uri::factory($serverPhoto['upload_url']);
        $client = new Zend_Http_Client($uploadUrl);
        $client->setFileUpload($image, 'photo');
        $result = $client->request('POST');
        $response = Zend_Json::decode($result->getBody());
        
        // формируем данные
        $data = array(
            'gid' => $this->_getParam('gid'),
            'server' => $response['server'],
            'photo' => $response['photo'],
            'hash' => $response['hash'],
            'access_token' => $this->getVkUser()->getAccessToken()
        );
        // сохраняем картинку
        $wallPhoto = $this->_vk->api('photos.saveWallPhoto', $data);
		$this->_log->info('Posting post in parser: vk api request (photos.saveWallPhoto) params (' . $this->_vk->getStrParams() . '); response=' . $this->_vk->getStrResponse());
        
        // постим
        $data = array(
            'owner_id' => '-' . $this->_getParam('gid'),
            'attachments' => $wallPhoto[0]['id'],
            'message' => $this->_getParam('text'),
            'from_group' => 1,
            'signed' => 0,
            'access_token' => $this->getVkUser()->getAccessToken()
        );
		
        $wall = $this->_vk->api('wall.post', $data);

        $this->_log->info('Posting post in parser: vk api request (wall.post) params (' . $this->_vk->getStrParams() . '); response=' . $this->_vk->getStrResponse());
		
		PostPeer::getInstance()->updatePost(
            $this->getVkUser(), 
            $lastInsertId, 
            $this->_getParam('text'), 
            $wallPhoto[0]['id'], 
            'http://vk.com/wall-' . $this->_getParam('gid') . '_' . $wall['post_id']
        );
		
		$this->_setAjaxResponse('ok');
	}
    
    /**
     * Обновляет данные поста
     * 
     * @param string $groupId
     * @param string $postId
     * @param string $postText
     * @param string $photoId
     * @param string $wallUrl 
     */
    private function _post($groupId, $postId, $postText, $photoId, $wallUrl)
    {
        $source = Page::getInstance()->getCurrentSource();
        $_SESSION[$source->key]['post'] = null;
        $_SESSION['current_group'] = $groupId;

        PostPeer::getInstance()->updatePost(
            $this->getVkUser(), 
            $postId, 
            $postText, 
            $photoId, 
            $wallUrl
        );
        $this->_log->info('Posting post: DB update post ' . $postId);
        $this->_redirect('/index/' . $source->key);
    }
    
    /**
     * Подтверждение капчи 
     */
    public function acceptCaptchaAction()
    {
        $this->_getLayout()->setLayout('login');
        $data = $this->_getActionParams();
        unset($data['/posting/accept_captcha']);
        unset($data['post_id']);
        // если есть captcha_key то пытаемся отправить запрос
        if ($this->_getParam('captcha_key')) {
            unset($data['captcha_img']);
            $wall = $this->_vk->api('wall.post', $data);
            $groupId = substr($this->_getParam('owner_id'), 1);
            $this->_post(
                $groupId, 
                $this->_getParam('post_id'),
                $data['message'],
                $data['attachments'],
                'http://vk.com/wall-' . $groupId . '_' . $wall['post_id']
            );
            $this->_log->info('Posting accept.captcha: send data to vk params(' . $this->_vk->getStrParams() . '); response=' . $this->_vk->getStrResponse());
        }
        $this->view->owner_id = $this->_getParam('owner_id');
        $this->view->attachments = $this->_getParam('attachments');
        $this->view->message = $this->_getParam('message');
        $this->view->from_group = $this->_getParam('from_group');
        $this->view->signed = $this->_getParam('signed');
        $this->view->access_token = $this->_getParam('access_token');
        $this->view->captcha_sid = $this->_getParam('captcha_sid');
        $this->view->captcha_img = $this->_getParam('captcha_img');
        $this->_log->info('Posting accept.captcha: view form');
    }
    
    /**
     * Отмечаем пост как удаленный
     * 
     * @throws Zend_Controller_Action_Exception 
     */
    public function delAction()
    {
        $this->_disableView();
        if (!$this->_getParam('pid')) {
            throw new Zend_Controller_Action_Exception('Параметр post id не указан');
        }
        
        $source = Page::getInstance()->getCurrentSource();
        $_SESSION[$source->key]['post'] = null;
        
        if ($this->_getParam('gid')) {
            $_SESSION['current_group'] = $this->_getParam('gid');
        }

        PostPeer::getInstance()->updateDel($this->_getParam('pid'), $this->getVkUser());
        $this->_log->info('Posting del: DB update post ' . $this->_getParam('pid'));
        $this->_redirect('/index/' . $source->key);
    }
    
    /**
     * Возвращаем пост по его ID
     * 
     * @throws Zend_Controller_Action_Exception 
     */
    public function getAction()
    {
        $this->_disableLayout();
        
        if (!$this->_getParam('id')) {
            throw new Zend_Controller_Action_Exception('Key ID is not set');
        }
        
        $row = PostPeer::getInstance()->findById($this->_getParam('id'));
        if ($row->count()) {
            $this->view->post = $row[0];
            $this->_log->info('Posting get: query post id = ' . $this->_getParam('id') . '; return ok');
        } else {
            $this->view->error = 'Post with the specified ID was not found';
            $this->_log->info('Posting get: query post id = ' . $this->_getParam('id') . '; return error');
        }
    }
}
